package sdfinal;

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;

public class Cliente extends JFrame {

	private static final long serialVersionUID = 1L;
	private JTextField tfBuscar;
	private JTextField tfDest;
        private JTextField tfMsg;
	private JButton btnBaixar;
	private JButton btnBuscar;
        private JButton btnDest;
        private JFileChooser dirSelect;
	private JList<String> lstServidores;
	private DefaultListModel<String> model = new DefaultListModel<String>();
	private ArrayList<ListServidor> servidores;
	private String arquivo;

	public Cliente() {
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setTitle("Servidor de Arquivos");
		setBounds(100, 200, 311, 250);
		JPanel contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(null);
		setContentPane(contentPane);

		JLabel lblArquivo = new JLabel("Arquivo");
		lblArquivo.setBounds(10, 11, 72, 14);
		contentPane.add(lblArquivo);

		JLabel lblDest = new JLabel("Destino");
		lblDest.setBounds(10, 51, 72, 14);
		contentPane.add(lblDest);

		tfBuscar = new JTextField();
		tfBuscar.setBounds(10, 25, 175, 20);
		contentPane.add(tfBuscar);

		tfDest = new JTextField();
		tfDest.setText(" ");
		tfDest.setBounds(10, 65, 175, 20);
		contentPane.add(tfDest);
                
		btnBuscar = new JButton("Buscar");
		btnBuscar.setBounds(195, 24, 89, 23);
		btnBuscar.addActionListener(new BotaoBuscar());
		contentPane.add(btnBuscar);

		btnBaixar = new JButton("Baixar");
		btnBaixar.setEnabled(false);
		btnBaixar.setBounds(10, 90, 89, 23);
		btnBaixar.addActionListener(new BotaoBaixar());
		contentPane.add(btnBaixar);
                
                btnDest = new JButton("Destino");
		btnDest.setBounds(195, 65, 89, 23);
		btnDest.addActionListener(new BotaoSelecionar());
		contentPane.add(btnDest);

		lstServidores = new JList<String>();
		lstServidores.setBounds(10, 130, 275, 89);
		lstServidores.setModel(model);
		contentPane.add(lstServidores);
                
                tfMsg = new JTextField();
		tfMsg.setText(" ");
                tfMsg.setBackground(Color.CYAN);
		tfMsg.setBounds(10, 225, 175, 20);
                tfMsg.setVisible(false);
		contentPane.add(tfMsg);
	}

	private class BotaoBuscar implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						btnBuscar.setEnabled(false);
                                                tfMsg.setVisible(true);
                                                tfMsg.setText("Procurando ...");

						Socket clientSocket = new Socket("localhost", 11111);
						DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
						arquivo = tfBuscar.getText();
						outToServer.writeBytes(arquivo + "\n");

						BufferedReader inFromServer = new BufferedReader(new InputStreamReader(
								clientSocket.getInputStream()));
						servidores = new ArrayList<ListServidor>();
						model.clear();
						String linha;
						String[] mensagem;
						while ((linha = inFromServer.readLine()) != null) {
							mensagem = linha.split(",");
							servidores.add(new ListServidor(mensagem[0], Integer.parseInt(mensagem[1])));
							model.addElement(mensagem[0]);
						}

						if (servidores.size() == 0) {
                                                        tfMsg.setVisible(true);
                                                        tfMsg.setText("Arquivo não existe");
						} else {
							tfMsg.setVisible(true);
                                                        tfMsg.setText("Arquivo localizado");
							btnBaixar.setEnabled(true);
							lstServidores.setSelectedIndex(0);
						}

						btnBuscar.setEnabled(true);
						clientSocket.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}).start();
		}
	}
        
        private class BotaoSelecionar implements ActionListener {
        
            public void actionPerformed(ActionEvent e)
            {
                dirSelect = new JFileChooser();
                dirSelect.setCurrentDirectory(new File("."));
                dirSelect.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                dirSelect.showOpenDialog(null);
                File selectedPfile = dirSelect.getSelectedFile();
                tfDest.setText(selectedPfile.getAbsolutePath());
            }
        }

	private class BotaoBaixar implements ActionListener {

		@Override
		public void actionPerformed(ActionEvent e) {
			Thread t = new Thread(new Runnable() {

				@Override
				public void run() {
					try {
						btnBuscar.setEnabled(false);
						btnBaixar.setEnabled(false);

						ListServidor servidor = servidores.get(lstServidores.getSelectedIndex());
						Socket socketDl = new Socket("localhost", servidor.porta);
						DataOutputStream out = new DataOutputStream(socketDl.getOutputStream());
						out.writeBytes(arquivo + "\n");

						BufferedInputStream bis = new BufferedInputStream(socketDl.getInputStream());
						FileOutputStream fos = new FileOutputStream(new File(tfDest.getText() + File.separator + arquivo));

						int i = 0;  
			            byte[] bytesIn = new byte[1024];  
			            while ((i = bis.read(bytesIn)) >= 0) {  
			                fos.write(bytesIn, 0, i);  
			            }

						bis.close();
						fos.close();
						socketDl.close();

						tfMsg.setVisible(true);
                                                tfMsg.setText("Download completo!!");
						tfBuscar.setText("");
						btnBuscar.setEnabled(true);
						model.clear();
					} catch (IOException e) {
						tfMsg.setVisible(true);
                                                tfMsg.setText("Erro no Download");
						e.printStackTrace();
					}
				}
			});
			t.start();
		}
	}
}